package com.csthink.web.infrastructure.filter;

import com.csthink.common.infrastructure.util.IDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.csthink.common.infrastructure.constant.Constants.REGION;
import static com.csthink.common.infrastructure.constant.Constants.TRACE_ID;
import static com.csthink.common.infrastructure.constant.JwtConstants.CST_TRACKING_ID;

/**
 * @author <a href="mailto:security.2009@live.cn">Mars</a>
 * @since 2023-09-14
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TracingFilter extends OncePerRequestFilter {

    @Value("${spring.application.name:}")
    private String applicationName;

    @Value("${aas.current-region:}")
    private String region;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String traceId = request.getHeader(CST_TRACKING_ID);
        if (StringUtils.isBlank(traceId)) {
            traceId = this.newTraceId();
        }

        this.setTraceId(traceId, response);
        response.addHeader(REGION, region);

        filterChain.doFilter(request, response);
    }

    private String newTraceId() {
        return applicationName + "_" + IDGenerator.getId();
    }

    private void setTraceId(String traceId, HttpServletResponse response) {
        MDC.put(TRACE_ID, traceId);
        MDC.put(CST_TRACKING_ID, traceId);
        response.setHeader(CST_TRACKING_ID, traceId);
    }
}
